<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts';
require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/util/util'

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    chartType: {
      type: String,
      default: 'ychart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: ''
    },
    taskName: {
      type: Array,
      default: () => {
        return []
      }
    },
    taskVal: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      chart: null
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  watch: {
    taskVal: {
      handler: function() {
        this.initChart()
      },
      deep: true
    }
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.chart.setOption({
        grid: {
          top: 10,
          bottom: 30,
          left: 150,
          right: 80
        },
        xAxis: {
          type: this.chartType === 'xchart' ? 'category':'value',
          data: this.chartType === 'xchart' ? this.taskName : [],
          splitLine:{show:false},
        },
        yAxis: {
          type: this.chartType === 'ychart' ? 'category':'value',
          data: this.chartType === 'ychart' ? this.taskName : [],
          minInterval: 1,
          axisLabel: {
            textStyle: {
              color: 'rgba(177, 245, 254, 1)'
            }
          },
          splitLine: false
        },
        series: [
          {
            type: 'bar',
            data: this.taskVal,
            label: {
              show: true,
              position: this.chartType === 'ychart' ? 'right':'inside',
              valueAnimation: true,
              textStyle: {
                color: '#ffffff',
                fontWeight: 'bold'
              },
            },
            itemStyle: {
              normal: {
                  color:function(){return "#"+Math.floor(Math.random()*(256*256*256-1)).toString(16);}
              }
            }
          }
        ]
      })
    }
  }
}
</script>
